//
//  HomePageController.swift
//  HappyEat
//
//  Created by ctx2016 on 17/1/6.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON

let k_Wide = UIScreen.main.bounds.size.width
let k_Height = UIScreen.main.bounds.size.height


class HomePageController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    
    let ActionCellId:String = "ActionCellId"
    let SelectedCellId:String = "SelectedCellId"
    let ScacleCellId:String = "ScaleCellId"
    var tableView:UITableView = UITableView.init()
    var headerView:UIView = UIView.init()//后期替换为轮播图
    //首页商品数据源
    var productDataSources:[HomePageProductModel] = [HomePageProductModel]()
    var netRequst:NetworkRequest{
        return NetworkRequest.shareInstance
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNaviBar()
        self.setUI()
        self.getHomeProduct()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension HomePageController{
    //MARK:设置导航左边的按钮
    func setNaviBar(){
        self.view.backgroundColor = .white
        self.navigationItem.title = "一元海吃"
        self.navigationController?.navigationBar.tintColor = UIColor.red
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "合肥", imagStr: "", fontSize: 16, target: self, action: #selector(leftBarButtonAction))
        self.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.white], for: .normal)
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
        self.navigationController?.navigationBar.barTintColor = UIColor.red
        //右边导航按钮
        let right_rBarButton:UIBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_M", fontSize: 40, target: self, action: #selector(right_rightBarButtonAction))
        let right_lBarbutton:UIBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_search", fontSize: 40, target: self, action: #selector(right_leftBarButtonAction))
        let navSpace:UIBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        navSpace.width = 20
        let rightBarButtons:[UIBarButtonItem] = [right_rBarButton,navSpace,right_lBarbutton]
        right_lBarbutton.width = 40
        self.navigationItem.rightBarButtonItems = rightBarButtons
        //取消导航栏背景黑色线
        self.navigationController?.navigationBar.shadowImage = UIImage.init()
        }
    ///MARK:导航栏三个按钮
    
    func leftBarButtonAction(){
        
    }
    func right_rightBarButtonAction(){
        let vc:MineMessageController = MineMessageController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func right_leftBarButtonAction(){
        
        }
    ///MARK:设置界面
    func setUI(){
        self.view.addSubview(self.tableView)
        self.headerView.frame = CGRect.init(x: 0, y: 0, width: k_Wide, height: 160)
        self.headerView.backgroundColor = .red
        self.tableView.tableHeaderView = headerView
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.snp.makeConstraints { (make) in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        }
//        self.tableView.backgroundColor = .orange
        self.tableView.tableFooterView = UIView.init()
        self.tableView.register(HomePageActionCell.self, forCellReuseIdentifier: ActionCellId)
        tableView.register(HomePageSelecCell.self, forCellReuseIdentifier: SelectedCellId)
        tableView.register(HomePageScaleCell.self, forCellReuseIdentifier: ScacleCellId)
    }
    //MARK:获取首页商品数据
    func getHomeProduct(){
        let params = ["sort":"0"]
        self.netRequst.postRequest(urlString: GetHomeProdect_URL, params: params, success:
            { (success) in
            print(success)
            print(JSON(success))
            let jsonData = JSON(success)
                if jsonData["status"].stringValue == "SUCCESS" {
                    //数据解析正确
                    self.productDataSources.removeAll()
                    for i in jsonData["data"].arrayValue{
                        let model:HomePageProductModel = HomePageProductModel.init(data: i)
                        self.productDataSources.append(model)
                        
                                                                }
                    //刷新首页商品数据源
                    self.tableView.reloadSections(IndexSet.init(integer: 2), with: .none)
                }else if jsonData["status"].stringValue == "ERROR" {
                    //数据解析错误
                }
            })
            { (error) in
                print(error)
        }
    }
    ///MARK:tableDelegate
    @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("")
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return 1
        case 2:
            //返回collectionView的个数
            return 1
        default:
            return 0
        }
    }
    @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell:HomePageActionCell = HomePageActionCell.init(style: .default, reuseIdentifier: ActionCellId)
            cell.selectionStyle = .none
            return cell
        case 1:
            let cell:HomePageSelecCell = HomePageSelecCell.init(style: .default, reuseIdentifier: SelectedCellId)
            cell.selectionStyle = .none
            return cell
        case 2:
            //更换为 Cell 嵌入 collectionView
            let cell:HomePageScaleCell = HomePageScaleCell.init(style: .default, reuseIdentifier: ScacleCellId)
            cell.backgroundColor = .white
            cell.selectionStyle = .none
            cell.dataSources = self.productDataSources
            return cell
        default:
            return UITableViewCell.init()
        }
    }
    @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return 24+55+8+14
        case 1:
            return 40
        case 2:
//            return (75 + 24)
            if self.productDataSources.count < 1{
                return 0
            }
            let count = self.productDataSources.count
//            128 + 12 + 3*(k_Wide/2)/4
//            return (count * 128) + ((count - 1) * (k_Wide/8) + 1)
            let itemCount = Int(count/2)
            return  CGFloat(CGFloat(itemCount) * (128 + 13 + 3*(k_Wide/2)/4))
        default:
            return 0
        }
    }
}
